#include "StdAfx.h"
#include "ServerSideUserList.h"
#include "Helper.h"

CServerSideUserList::CServerSideUserList(void)
{
	loadXML();
}

CServerSideUserList::~CServerSideUserList(void)
{
}
CServerSideUserList* CServerSideUserList::inst;
void CServerSideUserList::Push(CServerSideUser *iUser)
{
	_list.push_back(iUser);
}
void CServerSideUserList::ToChar(char* iOutString)
{
	char* result = new char[300];
	result[0] = 0;
	char* iTemp = new char[20];
	for (int i = 0;i<_list.size();i++)
	{
		if (_list[i]->IsOnline())
			_list[i]->ToCharSimple(iTemp);
		strcat(result,iTemp);
		strcat(result,"!");
	}
	if (strlen(result)>0)
		result[strlen(result)-1] = 0;
	strcpy(iOutString,result);
}
CServerSideUser* CServerSideUserList::GetByIndex(int iIndex)
{
	return _list[iIndex];
}
int CServerSideUserList::Find(char* iUserName)
{
	for (int i = 0;i<_list.size();i++)
	{
		if (_list[i]->CompareByUserName(iUserName))
			return i;
	}
	return -1;
}

void CServerSideUserList::loadXML()
{
	char* userName=new char[1];
	CServerSideUser* user;
	char* pass=new char[1];
	xmlUserList.Load(MCD_T("userList.xml"));
	xmlUserList.FindElem();
	xmlUserList.IntoElem();
	while(xmlUserList.FindElem(MCD_T("USER"))){
		user=new CServerSideUser;
		xmlUserList.IntoElem();

		xmlUserList.FindElem(MCD_T("UserName"));
		CHelper::ConverToChar(xmlUserList.GetData().c_str(),userName);
		user->SetUserName(userName);

		xmlUserList.FindElem(MCD_T("PassWord"));
		CHelper::ConverToChar(xmlUserList.GetData().c_str(),pass);
		user->SetPassword(pass);

		xmlUserList.OutOfElem();
		Push(user);
	}
}

bool CServerSideUserList::CheckUser( char* _username, char* _pass )
{
	int result=Find(_username);
	if (result==-1)
	{
		return false;
	}	
	CServerSideUser* user=_list[result];
	if (user->CompareByPassWord(_pass))
	{
		return true;
	}
	return false;
}
